package qhdx.fiveGC.controller;

import qhdx.fiveGC.entity.Banner;
import qhdx.fiveGC.mapper.BannerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
public class BannerController {
    @Autowired(required = false)
    BannerMapper mapper;

    @RequestMapping("/banner/select")
    public List<Banner> select(){
        return mapper.select();
    }

    @RequestMapping("/banner/delete")
    public void delete(int id){
        //得到图片的url
        String url = mapper.selectUrlById(id);
        //得到图片的完整路径
        String filePath = "F:/upload"+url;
        //删除文件
        new File(filePath).delete();

        mapper.delete(id);
    }
    @RequestMapping("/banner/add")
    public void add(MultipartFile picFile) throws IOException {
        //得到原始文件名
        String fileName = picFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;
        //保存图片的文件夹
        String dirPath = "F:/upload/";
        File dirFile = new File(dirPath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //文件完整路径
        String filePath = dirPath+fileName;
        //保存文件 异常抛出
        picFile.transferTo(new File(filePath));

        //把轮播图数据保存到数据库里面
        Banner banner = new Banner();
        banner.setUrl("/"+fileName);
        mapper.insert(banner);

    }

}
